package com.college.collegeinfomanage.util;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    public  static final  String  SING = "123321qwertyuiopasdfghjklzxcvbnm";

    // 请求进入前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenHeader = request.getHeader("Authorization"); // 取出 token 所在的请求头

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (tokenHeader == null || "".equals(tokenHeader)) {
            // 返回错误信息
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write("{\"message\": \"请求头中不存在 token 或 token 不正确!\"}");
            return false;
        }


        // 处理 Authorization 头部前缀，有则去掉 "Bearer "
        String token;
        if (tokenHeader.startsWith("Bearer ")) {
            token = tokenHeader.substring(7); // 从第 7 个字符开始截取，去掉 "Bearer "
        } else {
            token = tokenHeader; // 若不包含 "Bearer " 前缀，直接使用原字符串
        }

        // 验证 token 合法性
        try {
            boolean isValid = JWTUtil.verify(token, SING.getBytes());
            if (isValid) {
                return true;
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter pw = response.getWriter();
                pw.write("{\"message\": \"token 验证失败!\"}");
                return false;
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write("{\"message\": \"token 解析出错: " + e.getMessage() + "\"}");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}